<template>
  <div class="sm_boxSquare" ref="boxAreaRef">
    <div class="sm_bar" @click="showBoxFn">
      <div v-show="state.optTimes.length <= 0 || !state.optTimes" class="sm_placeh_text">{{ $props.placeholder }} </div>
      <template v-if="!$props.collapseTags">
        <el-tag v-for="(tag, index) in state.optTimes" :closable="$props.collapseTagsClose" :key="tag"
          class="sm_tag" :disable-transitions="false" @close="handleClose(tag, index)">
          {{ tag }}
        </el-tag>
      </template>
      <template v-else>
        <el-tag v-for="(tag, index) in state.optTimes.slice(0, $props.maxCollapseTags)" :key="tag"
          :closable="$props.collapseTagsClose" class="sm_tag" :disable-transitions="false"
          @close="handleClose(tag, index)">
          {{ tag }}
        </el-tag>
        <el-tag v-if="state.optTimes.length > $props.maxCollapseTags" class="sm_tag" :disable-transitions="false">
          +{{ state.optTimes.length - $props.maxCollapseTags }}
        </el-tag>
      </template>
    </div>
    <!-- 年份月份选择弹框 -->
    <div class="sm_contentBox" v-if="state.showBox"
      :style="{ left: state.boxOffect.left + 'px', top: state.boxOffect.top + 40 + 'px' }">
      <div class="sm_contentArea">
        <!-- 年份 -->
        <div class="sm_title">
          <el-icon v-if="state.curIndex == state.optTime.length - 1" class="sm_cursor" color="#E5EAF3">
            <ArrowLeft />
          </el-icon>
          <el-icon class="sm_cursor" v-else @click="reduceYear">
            <ArrowLeft />
          </el-icon>
          <div>{{ state.OneY }}年</div>
          <el-icon class="sm_cursor " v-if="state.curIndex == 0" color="#E5EAF3">
            <ArrowRight />
          </el-icon>
          <el-icon v-else class="sm_cursor" @click="addYear">
            <ArrowRight />
          </el-icon>
        </div>
        <!-- 月份 -->
        <div class="sm_conterList">
          <el-checkbox-group class="sm_selectbar" v-model="state.optTime[state.curIndex].queryTime" @change="onChange">
            <el-checkbox class="sm_onSelect" v-for="(item, index) in state.DateList[state.curIndex].queryTime"
              :key="index" :label="`${state.DateList[state.curIndex].TimeYear}-${(item <= 9) ? `0${item}` : item}`">
              {{ state.monthMap[item] }}月
            </el-checkbox>
          </el-checkbox-group>
        </div>
      </div>
      <!-- 按钮 -->
      <div class="sm_buttonBox">
        <el-button class="buttonStyle" type="primary" plain @click.stop="handleSubmit">确定</el-button>
        <el-button class="buttonStyle" plain @click.stop="reset">重置</el-button>
      </div>
    </div>
  </div>
</template>
<script setup>
import { ArrowLeft, ArrowRight } from '@element-plus/icons-vue'
import { onBeforeMount, ref,onMounted, watch, reactive } from 'vue'
const boxAreaRef=ref(null)
const props = defineProps({
  modelValue: {
    type: Array,
    default: () => []
  },
  collapseTagsClose: { // Tag 是否可关闭，默认为true
    type: Boolean,
    default: true
  },
  collapseTags: Boolean, // 多选时是否将选中值按文字的形式展示
  maxCollapseTags: {
    type: [Number, String],//需要显示的 Tag 的最大数量 只有当 collapse-tags 设置为 true 时才会生效。
    default: 1
  },
  placeholder: {
    type: String,
    default: '请选择'
  }
})

const state = reactive({
  DateList: [], // 年份月份数组
  optTime: [], // 月份选中结果数组
  OneY: '', // 当前年份
  curIndex: 20, // 当前年份下标值
  optTimes: [], // 点击月份时的所有选中结果
  resultTimes: [], // 点击“确定”按钮后的选择结果
  showBox: false, // 是否显示月份选择弹框
  showClear: false, // 是否显示输入框右边的“清空”小图标
  monthMap: { // 月份显示为中文
    '1': '一',
    '2': '二',
    '3': '三',
    '4': '四',
    '5': '五',
    '6': '六',
    '7': '七',
    '8': '八',
    '9': '九',
    '10': '十',
    '11': '十一',
    '12': '十二',
  },
  boxOffect: {
    left: 0,
    top: 0
  }
})

onBeforeMount(() => {
  init()
  watch(() => props.modelValue, (nv) => {
    if (nv && nv.length > 0) {
      state.resultTimes = nv
      resetMouth()
    } else {
      reset()
    }
  }, { immediate: true, deep: true })
})
const emit = defineEmits(['update:modelValue'])
// 关闭任意tag
const handleClose = (tag, index) => {
  state.resultTimes.splice(index, 1)
  resetMouth()
}
const showBoxFn = () => {
  state.boxOffect.left = boxAreaRef.value.getBoundingClientRect().left
  state.boxOffect.top = boxAreaRef.value.getBoundingClientRect().top
  state.showBox = !state.showBox
}
onMounted(() => {
  //点击弹框外的任意位置关闭区域弹窗
  document.addEventListener('click', (e) => {
    if (boxAreaRef.value && !boxAreaRef.value.contains(e.target)) {
      let equalArr = state.resultTimes.sort().toString() == state.optTimes.sort().toString()
      if (!equalArr) {
        resetMouth()
      }
      state.showBox = false
    }
  })

})
// 根据resultTimes 重置月份
const resetMouth = () => {
  state.optTimes = state.resultTimes
  let _opt = state.resultTimes.map(v => { return v.substring(0, 4) })
  for (let item in state.optTime) {
    state.optTime[item].queryTime = []
    _opt.map((items, indexs) => {
      if (items == state.optTime[item].TimeYear) {
        state.optTime[item].queryTime.push(state.resultTimes[indexs])
      }
    })
  }
}

const init = () => {
  let _opt = []
  let _optTime = []
  let arr = new Array(12)
  let optDate = getDateList()
  optDate.map((item, index) => {
    _optTime[index] = {
      TimeYear: item,
      queryTime: []
    }
    _opt[index] = {
      TimeYear: item,
      queryTime: []
    }
    for (let i = 1; i <= arr.length; i++) {
      _opt[index].queryTime.push(i)
    }
  })
  state.optTime = _optTime
  state.DateList = _opt
  if (props.modelValue && props.modelValue.length > 0) {
    resetMouth()
  }
}
// 获取前后20年年份列表，倒序排列，最新一年在最前面
const getDateList = () => {
  let Dates = new Date()
  let year = Dates.getFullYear()
  state.OneY = year
  let optDate = []
  for (let i = year - 20; i <= year + 20; i++) {
    optDate.push(i)
  }
  return optDate.reverse()
}
// 确定
const handleSubmit = () => {
  state.resultTimes = state.optTimes
  state.showBox = false
  emit('update:modelValue', state.resultTimes)
}
// 重置
const reset = () => {
  // 将年份重置到当前年份
  let Dates = new Date()
  let year = Dates.getFullYear()
  state.OneY = year
  state.optTimes = []
  for (let i in state.optTime) {
    state.optTime[i].queryTime = []
  }
  state.resultTimes = []
  state.showBox = false
  emit('update:modelValue', state.resultTimes)
}
// 左上角年份减少
const reduceYear = () => {
  // 如果已经是最后一年了，则年份不能再减少了
  if (state.curIndex == state.DateList.length - 1) return
  // 当前下标值+1，根据下标值获取年份值
  state.curIndex = state.curIndex + 1
  state.OneY = state.DateList[state.curIndex].TimeYear
}
// 左上角年份增加
const addYear = () => {
  // 如果已经是当前年份了，则年份不能再增加了
  if (state.curIndex == 0) return
  // 当前下标值-1，根据下标值获取年份值
  state.curIndex = state.curIndex - 1
  state.OneY = state.DateList[state.curIndex].TimeYear
}
// 选择月份
const onChange = () => {
  // 遍历optTime中已选择的月份，将已选结果塞到optTimes数组中
  let _opt = state.optTime
  let arr = []
  for (let item in _opt) {
    if (_opt[item].queryTime.length > 0) _opt[item].queryTime.filter(v => { arr.push(v) })
  }
  state.optTimes = arr
}
defineExpose({ reset })
</script>
<script>
export default {
  name: 'SelectMonths' // 月份多选
}
</script>
<style lang="scss" scoped>
.sm_title {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  padding: 15px 10px;
  border-bottom: 1px solid #e5e5e5;
}

.sm_selectbar {
  display: flex;
  flex-wrap: wrap;
}

 
.sm_boxSquare {
  position: relative;
  width: 200px;

}
.sm_contentBox {
  position: fixed;
  top: 40px;
  left: 0;
  z-index: 2021;
  background: #ffffff;
  border: 1px solid #e5e5e5;
  border-radius: 3px;
  z-index: 9999;

  .sm_contentArea {
    width: 330px;
  }
}

.sm_conterList {
  .sm_onSelect {
    width: 25% !important;
    margin: 20px 0 !important;
    display: flex;
    -ms-flex-pack: center;
    justify-content: center;
  }
}

.sm_buttonBox {
  border-top: 1px solid #e5e5e5;
  padding: 10px 10px 10px 0;
  text-align: right;
}

.sm_cursor {
  cursor: pointer;
  width: 30px;
  text-align: center;
}

.sm_bar {
  border: 1px solid var(--el-border-color);
  line-height: 28px;
  border-radius: 3px;
  overflow: auto;
  padding: 0 2px 1px 2px;
  min-width: 200px;
  width: 100%;
  height: auto;

}
.sm_tag {
  margin: 0 2px;
}

.sm_placeh_text {
  padding: 0 10px;
  color: #CFD3DC;
  line-height: 28px;
  font-size: 14px;
}
::v-deep(.el-checkbox__input){
  display: none;
}
</style>